package com.eight.controller.api;

import cn.hutool.json.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.eight.config.AliPayConfig;
import com.eight.pojo.TbOrder;
import com.eight.service.AliPayService;
import com.eight.service.OrderService;
import com.eight.util.WebUtil;
import com.eight.vo.ComResult;
import com.eight.vo.OrderPayVo;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

import static com.eight.config.AliPayConfig.*;

@RestController
@RequestMapping("/system/payment")
public class AlipayController {
    @Autowired
    private OrderService ordersService;
    @Autowired
    private AliPayService alipayService;
    @Autowired
    StringRedisTemplate redisTemplate;



    @RequestMapping(value="/pay")
    @ResponseBody
    public ComResult aliPay(@RequestBody OrderPayVo tbOrder) throws AlipayApiException {

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AliPayConfig.gatewayUrl, AliPayConfig.app_id, AliPayConfig.merchant_private_key, "json", AliPayConfig.charset, alipay_public_key, sign_type);
        //商户订单号，，必填
        String order_number = new String(tbOrder.getOrderNo());
        //付款金额，从前台获取，必填
        String total_amount = new String(tbOrder.getPreparidAmount().toString());
        //订单名称，必填
        String subject = new String("平价租车");
        System.out.println(order_number+total_amount+subject+"=========>");
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        request.setReturnUrl(return_url);
        JSONObject bizContent = new JSONObject();
        //商户订单号，商家自定义，保持唯一性
        bizContent.put("out_trade_no", order_number);
        //支付金额，最小值0.01元
        bizContent.put("total_amount", total_amount);
        //订单标题，不可使用特殊符号
        bizContent.put("subject",subject );
        request.setBizContent(bizContent.toString());
        AlipayTradePrecreateResponse response = alipayClient.execute(request);
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        //输出
//        log.info("返回结果={}",response);
        System.out.println(response.getQrCode());
//        HttpServletResponse response1 = WebUtil.getResponse();
//        PrintWriter writer = response1.getWriter();
//        String payCode = JSON.toJSONString();
//        writer.println(payCode);
//        writer.flush();
//        writer.close();
         return new ComResult(2000,"11",response.getQrCode());
    }

    @RequestMapping("/returnUrl")
    public ComResult isOrderPay(@RequestBody OrderPayVo order) throws AlipayApiException, IOException {
        if (alipayService.IsPay(order)){
            TbOrder tbOrder = new TbOrder();
            tbOrder.setOrderNo(order.getOrderNo());
            tbOrder.setState(1);
            int i = ordersService.updateStateByOrderNo(tbOrder);
            System.out.println("支付成功了");
            redisTemplate.opsForValue().set(order.getOrderNo(),"",30, TimeUnit.MINUTES);
            return new ComResult(2000, "支付成功good",i);
        }else {
            System.out.println("支付失败了");
            return new ComResult(5000, "支付失败bed" );
        }
    }

    /**
     *  确认订单是否支付
     * @param order 内有订单号
     * @return 返回订单是否已经支付
     * @throws AlipayApiException ali异常
     * @throws IOException 普通异常
     */
    @PostMapping("/isPay")
    public boolean isPay(@RequestBody OrderPayVo order)  {
        boolean b = false;
        try {
             b = alipayService.IsPay(order);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        return b;
    }


}
